from google.appengine.ext import db
from time import gmtime, strftime
from exceptions import *
from db.invoiceData import InvoiceData
from db.aziendaData import AziendaData
from db.sessionData import SessionData

import datetime, time

class ProjectData(db.Model):
	customer = db.ReferenceProperty(reference_class=AziendaData)
	user = db.UserProperty()
	name = db.StringProperty()
	closed = db.BooleanProperty(default=False)
	progress_work = db.IntegerProperty(default=0)
	last_operation = db.DateTimeProperty(auto_now=True)
	deleted = db.BooleanProperty(default=False)

	# per cifra fatturazione
	#eur = db.FloatProperty(0)
	unatantum = db.IntegerProperty(default=1)
	#irpef4percent = db.BooleanProperty(default=False)
	#marcadabollo = db.BooleanProperty(default=False)
	
	invoice = db.ReferenceProperty(reference_class=InvoiceData)
	
	@staticmethod
	def getProjectData(user, **trash):
		return map(lambda x: x.myserialize(), ProjectData.all().filter('user', user).filter("deleted =", False).order('name'))

	@staticmethod
	def getSingleProjectRawData(user, key):
		project = db.get(key)
		if project and user==project.user:
			return project
		return None
	
	@staticmethod
	def deleteProjectData(user, key=None, **trash):
		print key, trash
		if key:
			model = db.get(key)
			model.deleted = True
			model.put()
		else:
			raise MyException("Inexistent key")
	
	@staticmethod
	def newProject(user, key=None, customer=None, name=None, closed=False, eur=0, unatantum=False, progress_work=None, **trash):
		projectdatadb, new = key and (db.get(key), False) or (ProjectData(), True)
		projectdatadb.user = user
		if name:
			projectdatadb.name = name
		if not projectdatadb.name:
			raise NoNameProgettoException()
		if customer:
			projectdatadb.customer = db.get(customer)
		if progress_work:
			projectdatadb.progress_work = progress_work
		if closed != None:
			projectdatadb.closed = closed
		if eur:
			try:
				projectdatadb.eur = float(eur)
			except:
				raise WrongAmountFormatException()
		if unatantum not in [None, ""]:
			projectdatadb.unatantum = int(unatantum)
		projectdatadb.put()
		return [projectdatadb.myserialize()]


	def myserialize(self):
		return {
				'key':str(self.key()),
				'name':str(self.name),
				'customer': self.customer and str(self.customer.key()) or None,
				'closed': self.closed,
				'unatantum': self.unatantum,
				'last_operation':self.last_operation.isoformat(),
				'progress_work':self.progress_work
			}